%Denna modul ansvarar för att starta upp alla agenter och initiera dom
%Innehåller även agent oberoende functioner
%% @doc This module are responsible for initiating all the agents 
%% and contains some usfull functions that the agents can use.


-module(bot).
-export([start/0, getValue/2,sleep/1]).

%% @doc This function initiates all agents then dies.
%% @spec start() -> Pid
%% @end
start() -> 
    Actuator  = actuator:init(),
    DevCards  = dev_cards:init(),
    %Nodagenter ska startas här
    INodes    = lists:map(fun nod:init/1,createNodIds()),
	Nodes	  = lists:zip(createNodIds(),INodes),
    Opponents = opponents:init(),
    Resources = resources:init(),
    Robber    = robber:init(),
    Trader    = trader:init(),
	Interface = interface:init(),
	Interface!{initIDs,[{actuator,Actuator}]},
    %Interface agent måste med också
	Parse_Message = msg:init("Apa","Bepa","0","localhost","\t",Interface),
    Actuator!{initIDs,[{devCards,DevCards},
                        {nodes,Nodes},
                        {opponents,Opponents},
                        {resources,Resources},
                        {robber,Robber},
                        {trader,Trader},
						{parse_message,Parse_Message}]
             },
    DevCards!{initIDs,[{opponents,Opponents},
                        {resources,Resources},
                        {robber,Robber},
						{nodes,Nodes}]
             },
    Resources!{initIDs,[{trader,Trader},
                        {devCards,DevCards},
						{parse_message,Parse_Message},
						{trader, Trader},
						{actuator,Actuator}]
              },
    Robber!{initIDs,[{devCards,DevCards},
                        {opponents,Opponents},
                        {nodes,Nodes}]
              },
	Trader!{initIDs,[{parse_message,Parse_Message}]},
    lists:map(fun(X) -> X!{addRoads,createRoadIds(),createNodIds()} end,INodes),
	Opponents!{initIDs,[{parse_message,Parse_Message}]},
	Parse_Message ! {joingame},
	Parse_Message ! {sitdown},
	Parse_Message ! {startgame}.


%% @doc Returns the value V from a lists of tuples, {K,V}, that matches the key K. 
%% Or false if the the list don't contain K.
%% @spec getValue(Key,[{K,V}]) -> V | false
%% @end
getValue(K,List) -> case lists:keyfind(K,1,List) of
						{_,Value} -> Value;
						false -> false
					end.

createNodIds() ->
	[39,56,73,90,107,124,141,37,54,71,88,105,122,139,156,173,35,52,69,86,103,120,137,154,171,188,205,50,67,84,101,118,135,152,169,186,203,220,82,99,116,133,150,167,184,201,218,114,131,148,165,182,199,216].

createRoadIds() ->
    [38,72,106,140,
   36,70,104,138,172,
  34,68,102,136,170,204,
   66,100,134,168,202,
    98,132,166,200].

%% @doc Sleeps the calling threed for T milliseconds.
%% @spec sleep(Time) -> true
%% @end
sleep(T) ->
    receive
    after
        T -> true
    end.

